package com.example.security.config;

import com.example.security.auth.JsonAuthenticationEntryPoint;
import com.example.security.handler.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 使用数据库保存用户信息以及读取信息方式
 * 返回json数据格式
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserDetailsService userService;

    @Autowired
    private LoginAuthenticationSuccessHandler loginAuthenticationSuccessHandler;

    @Autowired
    private LoginFailureAuthenticationFailureHandler loginFailureAuthenticationFailureHandler;

    @Autowired
    private AppLogoutSuccessHandler appLogoutSuccessHandler;

    @Autowired
    private AuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;

    @Autowired
    private AppLogoutHandler appLogoutHandler;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
    }

    @Autowired
    private JsonAuthenticationEntryPoint jsonAuthenticationEntryPoint;

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //开启httpBasic
        http.httpBasic().and();
        //关闭跨域
        http.csrf().disable();

        //设置自定义登录页面
        http.formLogin()
                .loginPage("/login.html")// 自定义登录页面路径
                //登录成功回调
                .successHandler(loginAuthenticationSuccessHandler)
                //登录验证失败回调
                .failureHandler(loginFailureAuthenticationFailureHandler)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(jsonAuthenticationEntryPoint)
                //
                .accessDeniedHandler(authenticationAccessDeniedHandler)
                .and()
                .logout().permitAll()
                .logoutSuccessHandler(appLogoutSuccessHandler)
                .addLogoutHandler(appLogoutHandler)
                //注销登录后，删除cookie
                .deleteCookies("JSESSIONID")
                .and()
                .authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
                //设置放路径，login.html页面如果不放行则报错将您重定向的次数过多
                .antMatchers("/login.html").permitAll()
                .antMatchers("/login/error").permitAll()
                .antMatchers("/logout").permitAll()
                .antMatchers("/js/**", "/css/**", "/images/**", "/fronts/**").permitAll()

                //设置路径需要权限访问
                .antMatchers("/users","/home","/others").hasAnyAuthority("ROLE_USER")
                //读取配置权限配置
                .antMatchers("/**").access("hasRole('ADMIN')")

                // 其余请求都需要身份验证
                .anyRequest().authenticated();


    }

    //认证密码  通过BCrypt加密 检验解密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }



}
